package com.new2i.database;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class SqlCustomUtils {
	
	Document document=null;
	
	public SqlCustomUtils(String xmlFilePath) throws DocumentException{
		
		SAXReader saxReader = new SAXReader();//sax璇诲彇
		
		document=saxReader.read(xmlFilePath);
	
		
	}
	
	/**
	 * 根据预处理sql中的？插入相应的值
	 * @param sql
	 * @param param
	 * @return
	 */
   public static String insertVal(String sql,String[] param){
		
		if(param==null) return sql;
		
		String returnStr;
		returnStr = sql;
	
		
			for(int i=0;i<param.length;i++){
				returnStr=returnStr.replaceFirst("\\?",param[i]);
				//System.out.println(returnStr);
			}
	
		
		return returnStr;
	}


 
public static String insertValForOne(String sql,String[] param){

	
	if(param==null) return sql;
	
	String returnStr;
	returnStr = sql;

	
		for(int i=0;i<param.length;i++){
			String regEx = "^[0-9]*$";
			Pattern pat = Pattern.compile(regEx);
			Matcher m = pat.matcher(param[i]);
			if(!m.matches()){
				param[i] ="'" + param[i] + "'" ;
			}
			returnStr=returnStr.replaceFirst("\\?",param[i]);
			//System.out.println(returnStr);
		}

	
	return returnStr;
}
	
     /**
	 * 读取SQL语句从XML文件中
	 * @param nodeXPath 要读取的sql在xml中的XPATH位置
	 * @return 返回SQL语句
	 * @throws DocumentException
	 */
	public String readSQL(String nodeXPath){		
		
		//xpath 閾炬帴灞炴�
		Node node=document.selectSingleNode(nodeXPath);
		
		return node.getText();
	}
	
	/**
	 * 读取SQL语句从XML文件中
	 * @param xmlFileName xml文件名
	 * @param nodeXPath node的XPATH
	 * @return 返回读取出来的SQL语句
	 * @throws DocumentException
	 */
	public static String readSQL(String xmlFileName,String nodeXPath) throws DocumentException{
		
		String classpath=SqlCustomUtils.class.getResource("/").getPath();
		
		String xmlpath=classpath.substring(0,classpath.indexOf("classes"))+"report-sql/"+xmlFileName;
		
		SAXReader saxReader = new SAXReader();//sax璇诲彇
		
		Document doc=saxReader.read(xmlpath);
		
		Node node=doc.selectSingleNode(nodeXPath);
		
		return node.getText();
	}
	
	
}
